package com.piece.core.session.config;

import com.piece.core.framework.constant.CookieConstants;
import com.piece.core.web.cookie.CookieSerializer;
import com.piece.core.web.properties.SecurityProperties;
import com.piece.core.session.filter.DefaultSessionRepositoryFilter;
import com.piece.core.session.repository.SessionRepositoryManager;
import com.piece.core.session.repository.TokenSessionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.session.web.http.CookieHttpSessionIdResolver;
import javax.servlet.ServletContext;

public class SessionAutoConfig {

    @Autowired
    private ServletContext servletContext;

    @Autowired
    protected SecurityProperties securityProperties;

    @Bean(value = "sessionRepository")
    public TokenSessionRepository tokenSessionRepository() {
        return new TokenSessionRepository();
    }

    @Bean(name = "cookieSerializer")
    public CookieSerializer cookieSerializer() {
        CookieSerializer tokenSerializer = new CookieSerializer();
        // sessionId名称
        tokenSerializer.setCookieName(CookieConstants.SESSION_KEY);
        tokenSerializer.setUseBase64Encoding(false);
        return tokenSerializer;
    }

    @Bean(name = "cookieHttpSessionIdResolver")
    public CookieHttpSessionIdResolver cookieHttpSessionIdResolver(CookieSerializer cookieSerializer) {
        CookieHttpSessionIdResolver cookieHttpSessionIdResolver = new CookieHttpSessionIdResolver();
        cookieHttpSessionIdResolver.setCookieSerializer(cookieSerializer);
        return cookieHttpSessionIdResolver;
    }

    @Bean(name = "springSessionRepositoryFilter")
    public DefaultSessionRepositoryFilter springSessionRepositoryFilter(@Qualifier("sessionRepository") TokenSessionRepository sessionRepository,
                                                                        CookieHttpSessionIdResolver cookieHttpSessionIdResolver) {
        DefaultSessionRepositoryFilter sessionRepositoryFilter = new DefaultSessionRepositoryFilter(sessionRepository);
        sessionRepositoryFilter.setServletContext(this.servletContext);
        sessionRepositoryFilter.setSecurityProperties(this.securityProperties);
        sessionRepositoryFilter.setHttpSessionIdResolver(cookieHttpSessionIdResolver);
        return sessionRepositoryFilter;
    }

    @Bean
    public SessionRepositoryManager sessionRepositoryManager(TokenSessionRepository sessionRepository) {
        return new SessionRepositoryManager(sessionRepository);
    }
}
